<?php

/**
 * 自动生成 WxEventOpenboxService
 * 
 * Apps/Common/Service/WxEventOpenboxService.class.php
 * Zix @ 2015-07-04
 */

namespace Common\Service;

class WxEventOpenboxService {

  private static $instance;
  var $name = '拆礼盒';
  var $type = 'Openbox';

  public static function instance() {
    if (self::$instance == null) {
      $instance = new WxEventOpenboxService();
    }

    return $instance;
  }

  function get_default_row() {
    return array(
      'keyword' => '拆礼盒',
      'icon' => './Public/wx_func/images/openbox_share.jpg',
      'name' => '拆礼盒活动开始了',
      'title' => '欢迎参加拆礼盒活动，祝您好运哦！',
      'awarding_rule' => '兑奖请联系我们，电话138********',
      'rule' => '此活动杜绝恶意刷礼盒，每个手机只能有一个微信号帮忙。',
      'info' => '亲，请点击进入拆礼盒活动页面，祝您好运哦！',
      'home_bg_img' => './Public/wx_func/images/openbox_bg.jpg',
      'box_bg_img' => './Public/wx_func/images/openbox_box_bg.jpg',
      'award_adv_img' => './Public/wx_func/images/openbox_adv.jpg',
      'end_title' => '拆礼盒活动已经结束了',
      'end_desc' => '亲，活动已经结束，请继续关注我们的后续活动哦。',
      'end_icon' => './Public/wx_func/images/openbox_share.jpg',
      'point' => 0 ,
      'start_time' => date('Y-m-d'),
      'end_time' => date('Y-m-d', strtotime('+1 month')),
      'total_take_user' => 0 , //参与活动总数
      'allow_take_oneday' => 0 , //用户每日可领取数量
      'allow_take_total' => 0 , //用户可领取总数
    );
  }

  function get_by_id($id) {
    $WxEventOpenbox = M('WxEventOpenbox');
    $data = $WxEventOpenbox->find($id);
    return $data ? $data : array();
  }

  function get_by_cond($config) {
    $default = array(
      'page' => 1,
      'page_size' => 6,
      'status' => '',
      'count' => FALSE,
      'order' => 'DESC',
      'sort' => 'id',
    );

    $config = extend($config, $default);

    $WxEventOpenbox = M('WxEventOpenbox');

    $where = array();

    if (!empty($config['status'])) {
      $where['status'] = $config['status'];
    }

    if ($config['count']) {
      return $WxEventOpenbox->where($where)->count();
    } else {
      $order = $config['sort'] . ' ' . $config['order'];
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ' , ' . $config['page_size'];
      $data = $WxEventOpenbox
          ->where($where)
          ->limit($limit)->order($order)->select();
      //echo $WxEventOpenbox->_sql();
      return $data ? $data : array();
    }
  }
  
  /**
   * 取获奖名单列表
   */
  function get_award_list_by_id( $event_id ) {
    $WxEventUser = M('WxEventUser');
    
    $where = [] ;
    $WxEventUser->field('eu.username , ')
      ->alias('eu')
      ->join('mer_user user on user.id = eu.user_id' , 'left')
      ->join('')
      ->where( $where )
      ->select();
  }
  
  function create($data, $is_ajax = true) {
    $WxEventOpenbox = M('WxEventOpenbox');
    $ret = $WxEventOpenbox->add($data);
    if ($is_ajax) {
      if ($ret) {
        return ajax_arr('添加成功', TRUE, array(
          'id' => $ret
        ));
      } else {
        return ajax_arr('添加失败', FALSE);
      }
    } else {
      if ($ret) {
        return $ret;
      } else {
        return 0;
      }
    }
  }

  function update($id, $data) {
    $WxEventOpenbox = M('WxEventOpenbox');

    $ret = $WxEventOpenbox->where("id = %d", $id)->save($data);
    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete($ids) {
    $WxEventOpenbox = M('WxEventOpenbox');
    $ret = $WxEventOpenbox->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('删除' . $ret . '行数据', TRUE);
    }
  }
  
  /**
   * 取用户盒子总数
   * @param type $user_id
   * @param type $event_id
   * @return type
   */
  function get_user_box_count( $user_id , $event_id  ) {
    $WxEventUserService = WxEventUserService::instance();
    return $WxEventUserService->count_by_user_type_id($user_id, $this->type , $event_id );
  }
    
  function take_box($event_id , $user_id , $expand ) {
    //检查活动是否结束
    $today = strtotime(date('Y-m-d'));
    $event_data = $this->get_by_id($event_id);
    if ( $today < strtotime($event_data['start_time']) ) {
      return ajax_arr('活动还未开始');
    }
    
    if ( $today > strtotime($event_data['end_time']) ) {
      return ajax_arr('活动已经结束');
    }
    
    //判断是否设置了 用户领取总数
    $WxEventUserService = WxEventUserService::instance();
    if ( $event_data['allow_take_total'] > 0  ) {
      $total_count = $WxEventUserService->count_by_user_type_id($user_id, $this->type , $event_id );
      if( $total_count['amount'] >= $event_data['allow_take_total'] ) {
        return ajax_arr('您只能领取 '.$total_count['amount'] .' 次');
      }
    }
    //判断是否设置了 用户每日领取数
    if( $event_data['allow_take_oneday'] > 0  ) {
      $today_count = $WxEventUserService->count_by_user_type_id($user_id, $this->type , $event_id , 'today');
      if( $today_count['amount'] >= $event_data['allow_take_oneday'] ) {
        return ajax_arr('您今天只能领取 '.$today_count['amount'] .' 次');
      }
    }

    //取可用奖品
    $WxEventAward = WxEventAwardService::instance();
    $award_data = $WxEventAward->get_by_cond(array(
      'event_type' => $this->type ,
      'event_id' => $event_id ,
      'have_remain' => 1 ,
    ));
    
    if ( empty( $award_data ) ) {
      return ajax_arr('奖品已经领完了');
    }
    
    //检查奖品 获得中奖率
    foreach( $award_data as $key => $row ) {
      $award_data[$key]['take_rate'] = $row['take_rate'] > 0 ? $row['take_rate'] : $row['remain_qty'] ;
    }
        
    //取中奖奖品
    $take_award_data = $this->get_rand($award_data);
    if ( empty( $take_award_data ) ) {
      return ajax_arr('抽取错误，请稍后再试');
    }
    $award_id = $take_award_data['id'];
    
    $WxEventUser = M('WxEventUser');
    $WxEventUser->startTrans();
    //减少奖品数量
    $sql1 = 'update wx_event_openbox set total_take_user = total_take_user + 1 where id = ' . $event_id ;
    $sql2 = 'update wx_event_award set taken_qty = taken_qty + 1 , remain_qty = remain_qty - 1 where id = ' . $award_id ;

    $sn = rand_string(16) ;
    if( $take_award_data['valid_type'] == 2 ) {
      //有兑换码的奖品
      $WxEventAwardSn = WxEventAwardSnService::instance();
      $sn = $WxEventAwardSn->get_one_sn($award_id);
      if ( empty( $sn ) ) {
        $WxEventUser->rollback();
        return ajax_arr('兑换码未找到');
      }
    }
    
    $data = array(
      'event_type' => $this->type ,
      'event_id' => $event_id ,
      'user_id' => $user_id ,
      'award_id' => $award_id ,
      'award_sn' =>  $sn ,
      'expand' => $expand ,
      'valid_start_time' => $take_award_data['valid_start_time'],
      'valid_end_time' => $take_award_data['valid_end_time'],
      'ipaddress' => get_client_ip(0 , TRUE),
      'create_time' => date('Y-m-d H:i:s')
    );
    //更新活动状态
    $ret1 = $WxEventUser->execute( $sql1 ); 
    //echo $WxEventUser->_sql();
    //更新奖品信息
    $ret2 = $WxEventUser->execute( $sql2 );
    //添加用户参与用户
    $ret3 = $WxEventUser->add( $data );
    if ( $ret1 && $ret2 && $ret3 ) {
      $WxEventUser->commit();
      return ajax_arr('礼盒领取成功' , TRUE , array(
        'data' => $take_award_data 
      ));
    } else {
      $WxEventUser->rollback();
      return ajax_arr('系统错误，请稍后再试');
    }

  }

  function get_rand($pro_arr) {
    $result = '';
    $pro_sum = 0 ;
    //概率数组的总概率精度
    foreach ( $pro_arr as $row ) {
      $pro_sum += $row['take_rate'];
    }
    //概率数组循环   
    foreach ($pro_arr as $key => $val) {
      $rand_num = mt_rand(1, $pro_sum);
      if ($rand_num <= $val['take_rate']) {
        $result = $pro_arr[$key];
        break;
      } else {
        $pro_sum -= $val['take_rate'] ;
      }
    }
    unset($pro_arr);
    return $result;
  }
  
  function auth_award( $event_user_id , $password ) {
    $WxEventUser = WxEventUserService::instance() ;
    $data = $WxEventUser->get_by_id( $event_user_id , TRUEs );
    if ( $password != $data['password'] ) {
      //密码不正确
      return ajax_arr('兑换密码不正确，请重试');
    }
    
    return $WxEventUser->set_award_auth($event_user_id);
  }


}
